Each script is a plain text file containing lines to be executed by the program (AutoHotkey.exe). A script may also contain hotkeys and hotstrings, or even consist entirely of them. However, in the absence of hotkeys and hotstrings, a script will perform its commands sequentially from top to bottom the moment it is launched.
The program loads the script into memory line by line, and each line may be up to 16,383 characters long. During loading, the script is optimized and validated. Any syntax errors will be displayed, and they must be corrected before the script can run.
After the script has been loaded, it begins executing at the top line, continuing until a Return, Exit, hotkey/hotstring label, or the physical end of the script is encountered (whichever comes first). This top portion of the script is referred to as the auto-execute section.
A script that is not persistent and that lacks hotkeys, hotstrings, OnMessage, and GUI will terminate after the auto-execute section has completed. Otherwise, it will stay running in an idle state, responding to events such as hotkeys, hotstrings, GUI events, custom menu items, and timers.
Every thread launched by a hotkey, hotstring, menu item, GUI event, or timer starts off fresh with the default values for the following attributes as set in the auto-execute section. If unset, the standard defaults will apply (as documented on each of the following pages): DetectHiddenWindows, DetectHiddenText, SetTitleMatchMode, SetBatchLines, SendMode, SetKeyDelay, SetMouseDelay, SetWinDelay, SetControlDelay, SetDefaultMouseSpeed, CoordMode, SetStoreCapslockMode, AutoTrim, SetFormat, StringCaseSense, Thread, and Critical.
If the auto-execute section takes a long time to complete (or never completes), the default values for the above settings will be put into effect after 100 milliseconds. Thus, it's usually best to make any desired changes to the defaults at the top of scripts that contain hotkeys, hotstrings, timers, or custom menu items. Also note that each thread retains its own collection of the above settings. Changes made to those settings will not affect other threads.
AutoHotkey's default escape character is accent/backtick (`), which is at the upper left corner of most English keyboards. Using this character rather than backslash avoids the need for double blackslashes in file paths.
Since commas and percent signs have special meaning in the AutoHotkey language, use `, to specify a literal comma and `% to specify a literal percent sign. One of the exceptions to this is MsgBox, which does not require commas to be escaped. Another exception is commas in the last parameter of any command: they do not need to be escaped. See #EscapeChar for a complete list of escape sequences.
Certain special characters are also produced by means of an escape sequence. The most common ones are `t (tab), `n (linefeed), and `r (carriage return).
Tip: The first comma of any command may be omitted. For example:
MsgBox This is ok. MsgBox, This is ok too (it has an explicit comma).
Scripts can be commented by using a semicolon at the beginning of a line. For example:
; This entire line is a comment.
Comments may also be added to the end of a command, in which case the semicolon must have at least one space or tab to its left. For example:
Run Notepad ; This is a comment on the same line as a command.
In addition, the /* and */ symbols can be used to comment out an entire section, but only if the symbols appear at the beginning of a line as in this example:
/* MsgBox, This line is commented out (disabled). MsgBox, This one too. */
Since comments are ignored when a script is launched, they do not impact performance or memory utilization.
The default comment character (semicolon) can be changed to some other character or string via #CommentFlag.
Long lines can be divided up into a collection of smaller ones to improve readability and maintainability. This does not reduce performance because split lines are merged in memory the moment the script launches.
Method #1 [v1.0.35.03+]: A line that starts with "and", "or", ||, &&, a comma, or a period is automatically merged with the line directly above it. In the following example, the second line is merged with the first because it begins with a comma:
FileAppend, This is the text to append.`n ; A comment is allowed here. , %A_ProgramFiles%\SomeApplication\LogFile.txt ; Comment.
Similarly, the following lines would get merged into a single line because the last two start with "and" or "or":
if (Color = "Red" or Color = "Green" or Color = "Blue" ; Comment. or Color = "Black" or Color = "Gray" or Color = "White") ; Comment. and ProductIsAvailableInColor(Product, Color) ; Comment.
Although the indentation used in the examples above is optional, it might improve clarity by indicating which lines belong to ones above them. Also, it is not necessary to include an extra space after each of the first two lines; the program does this automatically. Finally, blank lines or comments may be added between or at the end of any of the lines in the above examples.
Method #2: This method should be used to merge a large number of lines or when the lines are not suitable for Method #1. Although this method is especially useful for auto-replace hotstrings, it can also be used with any command or expression. For example:
; EXAMPLE #1: Var = ( Line 1 of the text. Line 2 of the text. By default, a linefeed (`n) is present between lines. ) ; EXAMPLE #2: FileAppend, ; The comma is required in this case. ( A line of text. By default, the hard carriage return (Enter) between the previous line and this one will be written to the file as a linefeed (`n). By default, the tab to the left of this line will also be written to the file (the same is true for spaces). By default, variable references such as %Var% are resolved to the variable's contents. ), C:\My File.txt
In the examples above, a series of lines is bounded at the top and bottom by a pair of parentheses. This is known as a continuation section. Notice that the bottom line contains FileAppend's last parameter after the closing parenthesis. This practice is optional; it is done in cases like this so that the comma will be seen as a parameter-delimiter rather than a literal comma.
The default behavior of a continuation section can be overridden by including one or more of the following options to the right of the section's opening parenthesis. If more than one option is present, separate each one from the previous with a space. For example: ( LTrim Join| %
Join: Specifies how lines should be connected together. If this option is omitted, each line except the last will be followed by a linefeed character (`n). If the word Join is specified by itself, lines are connected directly to each other without any characters in between. Otherwise, the word Join should be followed immediately by as many as 15 characters. For example, Join`s would insert a space after each line except the last (`s indicates a literal space -- it is a special escape sequence recognized only by Join). Another example is Join`r`n, which inserts CR+LF between lines. Similarly, Join| inserts a pipe between lines. To have the final line in the section also ended by a join-string, include a blank line immediately above the section's closing parenthesis.
LTrim: Omits spaces and tabs at the beginning of each line. This is primarily used to allow the continuation section to be indented. In v1.0.35.06+, this option may be turned on for multiple continuation sections by specifying #LTrim on a line by itself. #LTrim is positional: it affects all continuation sections physically beneath it. The setting may be turned off via #LTrim Off.
RTrim0 (RTrim followed by a zero): Turns off the omission of spaces and tabs from the end of each line.
Comments (or Comment or Com or C) [v1.0.45.03+]: Allows semicolon comments inside the continuation section (but not /*..*/). Such comments are entirely omitted from the joined result rather than being treated as literal text.
% (percent sign): Treats percent signs as literal rather than as variable references. This avoids the need to escape each percent sign to make it literal. This option is not needed in places where percent signs are already literal, such as auto-replace hotstrings.
, (comma): Treats commas as delimiters rather than as literal commas. This rarely-used option is necessary only for the commas between command parameters because in function calls, the type of comma does not matter. Also, this option transforms only those commas that actually delimit parameters. In other words, once the command's final parameter is reached (or there are no parameters), subsequent commas are treated as literal commas regardless of this option.
` (accent): Treats each backtick character literally rather than as an escape character. Specifying this option also prevents commas and percent signs from being explicitly and individually escaped. In addition, it prevents the translation of any explicitly specified escape sequences such as `r and `t.
Remarks
Escape sequences such as `n (linefeed) and `t (tab) are supported inside the continuation section except when the accent (`) option has been specified.
When the comment option is not present, semicolon and /*..*/ comments are not supported within the interior of a continuation section because they are seen as literal text. However, comments can be included on the bottom and top lines of the section. For example:
FileAppend, ; Comment. ; Comments are supported here in v1.0.35.06+. ( LTrim Join ; Comment. ; This is not a comment; it is literal. Include the word Comments in the line above to make it a comment. ), C:\File.txt ; Comment.
As a consequence of the above, semicolons never need to be escaped within a continuation section.
A continuation section cannot produce a line whose total length is greater than 16,383 characters (if it tries, the program will alert you the moment the script is launched). One way to work around this is to do a series of concatenatations into a variable. For example:
Var =
(
...
)
Var = %Var%`n ; Add more text to the variable via another continuation section.
(
...
)
FileAppend, %Var%, C:\My File.txt
Since a closing parenthesis indicates the end of a continuation section, to have a line start with literal closing parenthesis, precede it with an accent/backtick: `).
A continuation section can be immediately followed by a line containing the open-parenthesis of another continuation section. This allows the options mentioned above to be varied during the course of building a single line.
Known limitations: 1) The piecemeal construction of a continuation section by means of #Include is not supported; 2) The directives #DerefChar, #Delimiter, and #EscapeChar are not obeyed by continutation sections; only the default characters for each of these are recognized.
A script compiler (courtesy of Jonathan Bennett's AutoIt v3 source code) is included with the program. AutoIt v2 scripts are not supported, so if necessary, first auto-convert your .aut file to .ahk.
Once a script is compiled, it becomes a standalone executable; that is, it can be used even on machines where AutoHotkey is not installed (and such EXEs can be distributed or sold with no restrictions). The compilation process compresses and encrypts all of the following: the script, any files it includes, and any files it has incorporated via the FileInstall command.
Compiling does not improve the performance of a script. In fact, a compiled script is slightly slower to launch because it must first be decrypted and decompressed into memory, after which it is optimized just like a normal script.
Ahk2Exe can be used in the following ways:
Notes:
Scripts support command line parameters. The format is:
AutoHotkey.exe [Switches] [Script Filename] [Script Parameters]
And for compiled scripts, the format is:
CompiledScript.exe [Switches] [Script Parameters]
Switches: Zero or more of the following:
/f or /force -- Launch unconditionally, skipping any warning dialogs.
/r or /restart -- Indicate that the script is being restarted (this is also used by the Reload command, internally).
/ErrorStdOut -- Send syntax errors that prevent a script from launching to stdout rather than displaying a dialog. See #ErrorStdOut for details.
Script Filename: This can be omitted if there are no Script Parameters. If omitted, it will run (or prompt you to create) AutoHotkey.ini in the current working directory.
Script Parameters: The string(s) you want to pass into the script, with each separated from the next by a space. Any parameter that contains spaces should be enclosed in quotation marks. A literal quotation mark may be passed in by preceding it with a backslash (\"). Consequently, any trailing slash in a quoted parameter (such as "C:\My Documents\") is treated as a literal quotation mark (that is, the script would receive the string C:\My Documents"). To remove such quotes, use StringReplace, 1, 1, ",, All
The script sees incoming parameters as the variables %1%, %2%, and so on. In addition, %0% contains the number of parameters passed (0 if none). The following example exits the script when too few parameters are passed to it:
if 0 < 3 ; The left side of a non-expression if-statement is always the name of a variable.
{
MsgBox This script requires at least 3 incoming parameters but it only received %0%.
ExitApp
}
If the number of parameters passed into a script varies (perhaps due to the user dragging and dropping a set of files onto a script), the following example can be used to extract them one by one:
Loop, %0% ; For each parameter: { param := %A_Index% ; Fetch the contents of the variable whose name is contained in A_Index. MsgBox, 4,, Parameter number %A_Index% is %param%. Continue? IfMsgBox, No break }
If the parameters are file names, the following example can be used to convert them to their case-corrected long names (as stored in the file system), including complete/absolute path:
Loop %0% ; For each parameter (or file dropped onto a script): { GivenPath := %A_Index% ; Fetch the contents of the variable whose name is contained in A_Index. Loop %GivenPath% LongPath = %A_LoopFileLongPath% MsgBox The case-corrected long path name of file`n%GivenPath%`nis:`n%LongPath% }
Known limitation: dragging files onto a .ahk script may fail to work properly if 8-dot-3 (short) names have been turned off in an NTFS file system. One work-around is to compile the script then drag the files onto the resulting EXE.
Commands such as ListVars and Pause can help you debug a script. For example, the following two lines, when temporarily inserted at carefully chosen positions, create "break points" in the script:
ListVars
Pause
When the script encounters these two lines, it will display the current contents of all variables for your inspection. When you're ready to resume, un-pause the script via the File or Tray menu. The script will then continue until reaching the next "break point" (if any).
It is generally best to insert these "break points" at positions where the active window does not matter to the script, such as immediately before a WinActivate command. This allows the script to properly resume operation when you un-pause it.
The following commands are also useful for debugging: ListLines, KeyHistory, and OutputDebug.
The file AutoHotkey.exe is all that is needed to launch any .ahk script. The only exception is Windows NT4, which requires a copy of psapi.dll (from the AutoHotkey folder) for any script that uses the Process command.
To silently install AutoHotkey into the default directory (which is the same directory displayed by non-silent mode), pass the parameter /S to the installer (/S must be capitalized). For example:
AutoHotkey104307_Install.exe /S
A directory other than the default may be specified via the /D parameter (in the absence of /S, this changes the default directory displayed by the installer). For example:
AutoHotkey104307_Install.exe /S /D=C:\Program Files\AutoHotkey
To silently uninstall AutoHotkey, pass the parameter /S to the uninstaller. For example:
"C:\Program Files\AutoHotkey\uninst.exe" /S
See this page for some useful scripts.